import { ref, nextTick } from "vue"
import { getChatList, sendMsg as sednChatMsg } from "../../service/user"
import { useUserStore } from "../../store/user"

export const useChatCardHook = () => {
  const userStore = useUserStore()
  const userInfo: any = userStore.userInfo

  const replyMsg = ref("")

  const msgList = ref([])

  const loading = ref(false)

  const getChatData = async () => {
    loading.value = true
    await getChatList({ userId: userInfo.userId }).then(res => {
      msgList.value = res.data
    })

    loading.value = false
  }

  getChatData()


  const sendLoading = ref(false)
  const sendMsg = async (el: any, e: any) => {
    if (!replyMsg.value.length) return
    sendLoading.value = true
    if (e) e.preventDefault();

    await sednChatMsg({ content: replyMsg.value, type: "1" })

    await getChatList({ userId: userInfo.userId }).then(res => {
      msgList.value = res.data
    })

    sendLoading.value = false
    el.scrollTop = el.scrollHeight;
    replyMsg.value = ""
  }

  return { replyMsg, msgList, sendMsg, loading, sendLoading }
}
